package com.bysj.servelt;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bysj.model.Data;
import com.bysj.model.Goods;
import com.bysj.model.Page;
import com.bysj.model.User;
import com.bysj.service.GoodsService;

/**
 * Servlet implementation class IndexServlet
 */
@WebServlet("/index")
public class IndexServlet extends HttpServlet {

	private GoodsService gService = new GoodsService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 取得推荐商品
		User user = (User) request.getSession().getAttribute("user");
		if (user != null && !user.isIsnew()) {
			List<Integer> ids = getRecommendGoogs(user.getId());
			if (ids.size() > 0) {
				List<Goods> scrollGoods = gService.getByIds(ids);
				request.setAttribute("goodsList", scrollGoods);
			}
		}
		User u = (User) request.getSession().getAttribute("user");
		if (u == null) {
			request.getRequestDispatcher("/user_login.jsp").forward(request, response);
			return;
		}
		// 取得热销商品
		Page hotPage = gService.getGoodsRecommendPage(2, 1);
		request.setAttribute("hotList", hotPage.getList());

		// 取得新品商品
		Page newPage = gService.getGoodsRecommendPage(3, 1);
		request.setAttribute("newList", newPage.getList());

		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	private static double[][] multiplyMatrix(int[][] a, double[][] b) {// 两个矩阵相乘
		if (a[0].length != b.length) {
			return null;
		}
		double[][] c = new double[a.length][b[0].length];
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < b[0].length; j++) {
				for (int k = 0; k < a[0].length; k++) {
					c[i][j] += a[i][k] * b[k][j];
				}
			}
		}
		return c;
	}

	private List<Integer> getRecommendGoogs(int userId) {
		List<Data> list = gService.findGoodsData();
		int m = 0;// 用户个数
		int n = 0;// 菜品个数
		for (Data vo : list) {
			if (m < vo.getUserId()) {
				m = vo.getUserId();
			}
			if (n < vo.getGoodsId()) {
				n = vo.getGoodsId();
			}
		}

		int R[][] = new int[m][n];// 用户-物品矩阵
		double S[][] = new double[n][n];// 物品相似度矩阵
		for (Data vo : list) {
			R[vo.getUserId() - 1][vo.getGoodsId() - 1] = vo.getAmountSum();
		}
		// 得到矩阵S
		for (int i = 0; i < n; i++) {
			S[i][i] = 0;
		}
		for (int i = 0; i < n; i++) {
			for (int j = i + 1; j < n; j++) {
				int useriyj = 0;// 同时购买物品i和物品j的用户数
				int userihj = 0;// 购买物品i或j的用户数（同时购买物品i和物品j的用户只算一个）
				for (int k = 0; k < m; k++) {
					if (R[k][i] != 0 && R[k][j] != 0) {
						useriyj++;
					}
					if (R[k][i] != 0 || R[k][j] != 0) {
						userihj++;
					}
				}
				if (userihj == 0 || useriyj == 0) {
					S[i][j] = 0;
				} else {
					S[i][j] = useriyj * 1.0 / userihj;
				}
				S[j][i] = S[i][j];
			}
		}

		// 用户对物品的预测评分矩阵
		double P[][] = multiplyMatrix(R, S);
		int u = userId - 1;
		// 取最大8个评分对应的goodsId
		TreeMap<Integer, Double> map = new TreeMap<Integer, Double>(Comparator.reverseOrder());
		for (int i = 0; i < n; i++) {
			if (P[u][i] > 0) {
				map.put(i + 1, P[u][i]);
			}
		}

		List<Integer> ids = new ArrayList<Integer>();
		for (int id : map.keySet()) {
			if (ids.size() < 8) {
				ids.add(id);
			}
		}

		return ids;
	}
}
